package com.example.flashsales.controller;

import com.example.flashsales.Tools.NumberUtil;
import com.example.flashsales.Tools.TokenTool;
import com.example.flashsales.entity.Result;
import com.example.flashsales.entity.dto.AdminDto;
import com.example.flashsales.entity.pojo.Admin;
import com.example.flashsales.entity.pojo.Method;
import com.example.flashsales.entity.pojo.Role;
import com.example.flashsales.entity.vo.AdminVo;
import com.example.flashsales.service.impl.RoleServiceImpl;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 权限分配
 */
@Controller
@RequestMapping("/role")
public class RoleController {
    @Autowired
    RoleServiceImpl roleService;


    /**
     * 登录
     * @param httpServletRequest
     * @param adminDto
     * @return
     */
    @ResponseBody
    @PostMapping("/login")
    public Result login(HttpServletRequest httpServletRequest, @RequestBody AdminDto adminDto, HttpServletResponse httpServletResponse){
        if (adminDto == null || adminDto.getPassword() == null || adminDto.getAccount() == null){
            return Result.error("请输入账号密码");
        }
        final Admin login = roleService.login(adminDto);
        if (login == null){
            return Result.error("账号密码错误");
        }
        if (login.getState() != 4){
            return Result.error("抱歉你没有权限");
        }
        if (login.getS() == 1){
            return Result.error("你已被禁止登录");
        }
        httpServletResponse.addHeader("Access-Control-Expose-Headers", "Token");
        //生成Token
        Map<String, String> map = new HashMap<>();
        map.put("id", login.getId() + "");
        map.put("state", login.getState() + "");
        httpServletResponse.setHeader("Token", TokenTool.createToken(map));
        return Result.ok("登录成功");
    }

    /**
     * 查看有哪些角色
     * @param httpServletRequest
     * @return
     */
    @ResponseBody
    @GetMapping("/viewAllRole")
    public Result viewAllRole(HttpServletRequest httpServletRequest){
        final List<Role> roles = roleService.viewAllRole();
        return Result.ok("查看成功").setData(roles);
    }

    /**
     * 注册后台人员 分配身份
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public Result registerAdmin(HttpServletRequest httpServletRequest, @RequestBody AdminDto adminDto){
//        System.out.println(adminDto.toString());
        if (adminDto == null || adminDto.getAccount() == null || adminDto.getPassword() == null || adminDto.getState() == null){
            return Result.error("请输入参数");
        }
        if (!NumberUtil.isPhone(adminDto.getAccount())) {
            return Result.error("请输入正确的电话号码");
        }
        Pattern pattern = Pattern.compile("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,}$");
        Matcher matcher = pattern.matcher(adminDto.getPassword());
        if (adminDto.getPassword().length() < 6 || !matcher.matches()){
            return Result.error("输入密码长度需大于等于6且含字母");
        }
        final List<Role> roles = roleService.viewAllRole();

        boolean flag = false;
        for (Role role : roles) {
            if (role.getId() == adminDto.getState()){
                flag = true;
            }
        }
        if (adminDto.getState() == 0){
            adminDto.setState(1);
        }
        if (!flag){
            return Result.error("没有该角色");
        }
        //判断是否存在
        if (roleService.viewAdminByAccount(adminDto.getAccount()) != null) {
            return Result.error("注册失败，账号已存在");
        }
        if (roleService.registerAdmin(adminDto)) {
            return Result.ok("注册成功");
        }
        return Result.error("注册失败");
    }

    /**
     * 冻结后台人员
     * @param httpServletRequest
     * @param adminId 后台人员id
     * @return
     */
    @ResponseBody
    @GetMapping("/freezeAdmin")
    public Result freezeAdmin(HttpServletRequest httpServletRequest,Integer adminId){
       if (adminId == null){
           return Result.error("请输入参数");
       }
        final Admin admin = roleService.viewAdminById(adminId);
       if (admin == null){
           return Result.error("用户不存在");
       }
       if (admin.getState() == 4){
           return Result.error("抱歉你没有权限操作");
       }
       if (admin.getS() == 1){
           return Result.error("操作失败，该人员已经被封号");
       }
        if (roleService.updateAdminState(adminId,1)) {
            return Result.ok("修改成功");
        }
        return Result.error("修改失败");
    }

    /**
     * 解冻后台人员
     * @param httpServletRequest
     * @param adminId 后台人员id
     * @return
     */
    @ResponseBody
    @GetMapping("/thawAdmin")
    public Result thawAdmin(HttpServletRequest httpServletRequest,Integer adminId){
        if (adminId == null){
            return Result.error("请输入参数");
        }
        final Admin admin = roleService.viewAdminById(adminId);
        if (admin == null){
            return Result.error("用户不存在");
        }
        if (admin.getState() == 4){
            return Result.error("抱歉你没有权限操作");
        }
        if (admin.getS() == 0){
            return Result.error("操作失败，该人员已经解封");
        }
        if (roleService.updateAdminState(adminId,0)) {
            return Result.ok("修改成功");
        }
        return Result.error("修改失败");
    }

    /**
     * 条件分页查询所有管理人员
     * @param httpServletRequest
     * @param page
     * @param num
     * @param adminId
     * @param phone
     * @return
     */
    @ResponseBody
    @GetMapping("/viewAllAdmin")
    public Result viewAllAdmin(HttpServletRequest httpServletRequest,@RequestParam(defaultValue = "1") Integer page,@RequestParam(defaultValue = "10") Integer num,@RequestParam(defaultValue = "0")Integer adminId,@RequestParam(defaultValue = "0")String phone,@RequestParam(defaultValue = "-1") Integer s,@RequestParam(defaultValue = "0")Integer state){
        if (page <= 0 || num < 0 || (!phone.equals("0") && !NumberUtil.isPhone(phone))){
            return Result.error("请输入正确的参数");
        }
        final List<AdminVo> adminVos = roleService.viewAllAdmin(page, num, adminId, phone, s,state);
        return Result.ok("查看成功").setData(new PageInfo<>(adminVos));
    }


    /**
     * 查看所有方法
     * @param httpServletRequest
     * @return
     */
    @GetMapping("/viewAllMethod")
    @ResponseBody
    public Result viewAllMethod(HttpServletRequest httpServletRequest){
        final List<Method> methods = roleService.viewAllMethod();
        return Result.ok("查看成功").setData(methods);
    }

    /**
     * 根据角色查看方法
     * @param httpServletRequest
     * @param state
     * @return
     */
    @ResponseBody
    @GetMapping("/viewMethodByState")
    public Result viewMethodByState(HttpServletRequest httpServletRequest,Integer state){
        if (state == null){
            return Result.error("请输入参数");
        }
        final List<Method> methods = roleService.viewMethodByState(state);
        return Result.ok("查看成功").setData(methods);
    }

    /**
     *  根据后台人员查看他拥有的方法
     * @param httpServletRequest
     * @param adminId
     * @return
     */
    @ResponseBody
    @GetMapping("/viewMethodByAdminYes")
    public Result viewMethodByAdminYes(HttpServletRequest httpServletRequest,Integer adminId){
        if(adminId == null){
            return Result.error("请输入参数");
        }
        final List<Method> methods = roleService.viewMethodByAdmin(adminId);
        return Result.ok("查看成功").setData(methods);
    }

    /**
     *  根据后台人员查看他没有的方法
     * @param httpServletRequest
     * @param adminId
     * @return
     */
    @ResponseBody
    @GetMapping("/viewMethodByAdminNo")
    public Result viewMethodByAdminNo(HttpServletRequest httpServletRequest,Integer adminId){
        if(adminId == null){
            return Result.error("请输入参数");
        }
        final List<Method> methods = roleService.viewMethodByAdminNo(adminId);
        return Result.ok("查看成功").setData(methods);
    }

    /**
     * 给后台人员添加方法
     * @param httpServletRequest
     * @param adminId
     * @param methodId
     * @return
     */
    @ResponseBody
    @GetMapping("/addMethodToAdmin")
    public Result addMethodToAdmin(HttpServletRequest httpServletRequest,Integer adminId,Integer methodId){
        if (adminId == null || methodId == null){
            return Result.error("请输入参数");
        }
        for (Method method : roleService.viewMethodByAdmin(adminId)) {
            if (method.getId() == methodId){
                return Result.error("添加失败 他已经拥有此方法");
            }
        }
        if (roleService.addMethodToAdmin(adminId,methodId,0)) {
            return Result.ok("添加成功");
        }
        return Result.error("添加失败");
    }


    /**
     * 给后台人员移除方法
     * @param httpServletRequest
     * @param adminId
     * @param methodId
     * @return
     */
    @ResponseBody
    @GetMapping("/deleteMethodToAdmin")
    public Result deleteMethodToAdmin(HttpServletRequest httpServletRequest,Integer adminId,Integer methodId){
        if (adminId == null || methodId == null){
            return Result.error("请输入参数");
        }
        for (Method method : roleService.viewMethodByAdminNo(adminId)) {
            if (method.getId() == methodId){
                return Result.error("移除失败 他没有此方法");
            }
        }
        if (roleService.addMethodToAdmin(adminId,methodId,1)) {
            return Result.ok("移除成功");
        }
        return Result.error("移除失败");
    }
}
